/*
 * Copyright 2020 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { order as orderApi, store } from "@mall/api-services"
import * as _ from "lodash"
import * as React from "react"
import { RouteComponentProps, withRouter } from "react-router"
import Flex from "../components/flex"
import NavBar from "../components/navbar"
import Panel from "../components/panel"
import Icon from "../icon"
import "./order-detail.scss"
import OrderItem from "./order-item"

interface OrderDetailProps extends RouteComponentProps {

}

interface OrderDetailState {
  order: orderApi.Order;
  storeInfo: store.Store;
}

class OrderDetail extends React.Component<OrderDetailProps, OrderDetailState> {

  public constructor(props: Readonly<OrderDetailProps>) {
    super(props)
    this.state = {
      order: new orderApi.Order(),
      storeInfo: new store.Store(),
    }
  }

  public componentDidMount(): void {
    this.refreshOrder()
  }

  public render() {
    const { history } = this.props
    const { order, storeInfo } = this.state
    const { shippingAddress } = order
    return (
      <div className="order-detail">
        <header>
          <NavBar left={<Icon type="left" onClick={() => history.goBack()}/>}>订单详情</NavBar>
        </header>
        <Panel className="shipping-address">
          <div>{shippingAddress.lastName} {shippingAddress.firstName} {shippingAddress.mobile}</div>
          <div className="address-location">地址:{shippingAddress.address}{shippingAddress.location}</div>
        </Panel>
        <Panel>
          <div className="">{storeInfo.name}</div>
          {_.map(order.items, item => <OrderItem key={item.id} item={item}/>)}
        </Panel>
        <Panel className="order-info">
          <Flex>
            <span className="order-property-name">订单编号:</span>
            <span>{order.id}</span>
          </Flex>
          <Flex>
            <span className="order-property-name">下单时间:</span>
            <span>{order.createdTime}</span>
          </Flex>
        </Panel>
      </div>
    )
  }

  private refreshOrder() {
    const { match } = this.props
    orderApi.OrderServiceV1
      .getOrder(match.params["order_id"])
      .then(order => store.StoreServiceV1.getStore(order.storeId)
        .then(storeInfo => this.setState({ order, storeInfo })))
  }
}

export default withRouter(OrderDetail)
